package com.himiotech.core.project.web.system.monitor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.himiotech.core.framework.config.shiro.session.OnlineSessionDao;
import com.himiotech.core.framework.helper.anno.Log;
import com.himiotech.core.framework.helper.enums.BusinessType;
import com.himiotech.core.framework.helper.utils.ExcelUtil;
import com.himiotech.core.framework.helper.utils.ShiroUtils;
import com.himiotech.core.project.model.entity.online.OnlineSession;
import com.himiotech.core.project.model.entity.online.UserOnline;
import com.himiotech.core.project.model.metadata.UserOnlineMetadata;
import com.himiotech.core.project.service.IUserOnlineService;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.UnknownSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 在线用户监控
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Controller
@RequestMapping("/monitor/online")
public class UserOnlineController extends HimioBaseController {

    @Autowired
    private IUserOnlineService userOnlineService;

    @Autowired
    private OnlineSessionDao onlineSessionDao;

    @RequiresPermissions("monitor:online:view")
    @GetMapping
    public String online() {
        return "monitor/online";
    }

    /**
     * 导出在线用户记录列表数据
     *
     * @param userOnline 查询条件
     * @return 导出数据
     */
    @Log(title = "在线用户记录 - 导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("monitor:online:export")
    @PostMapping("/export")
    @ResponseBody
    public HimioResult export(UserOnline userOnline) {
        QueryWrapper<UserOnline> query = Wrappers.query();
        if (userOnline != null) {
            query.like(ObjectUtil.isNotEmpty(userOnline.getLoginName()), UserOnlineMetadata.LOGIN_NAME.getColName(), userOnline.getLoginName());
            query.like(ObjectUtil.isNotEmpty(userOnline.getLoginLocation()), UserOnlineMetadata.LOGIN_LOCATION.getColName(), userOnline.getLoginLocation());
        }
        List<UserOnline> list = userOnlineService.list(query);
        ExcelUtil<UserOnline> util = new ExcelUtil<>(UserOnline.class);
        return util.exportExcel(list, "在线用户记录");
    }

    /**
     * 查询在线用户记录列表
     *
     * @param page       分页信息
     * @param userOnline 查询条件
     * @return 表格分页数据
     */
    @RequiresPermissions("monitor:online:list")
    @PostMapping("/list")
    @ResponseBody
    public HimioResult list(Page<UserOnline> page, UserOnline userOnline) {
        handleOrderBy(request, page);
        page = userOnlineService.selectUserOnlineListPage(page, userOnline);
        return writeJsonLayuiTable(page);
    }

    @RequiresPermissions(value = {"monitor:online:batchForceLogout", "monitor:online:forceLogout"}, logical = Logical.OR)
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @PostMapping("/batchForceLogout")
    @ResponseBody
    public HimioResult batchForceLogout(String ids) {
        for (String sessionId : Convert.toStrArray(ids.split(","))) {
            UserOnline online = userOnlineService.getById(sessionId);
            if (online == null) {
                return writeJsonErr("用户已下线");
            }
            OnlineSession onlineSession;
            try {
                onlineSession = (OnlineSession) onlineSessionDao.readSession(online.getSessionId());
            } catch (UnknownSessionException e) {
                userOnlineService.deleteOnlineById(online.getSessionId());
                return writeJsonOk("当前会话 session id [" + online.getSessionId() + "] 已不存在，清除成功！");
            }
            if (onlineSession == null) {
                return writeJsonErr("用户已下线");
            }
            if (sessionId.equals(ShiroUtils.getSessionId())) {
                return writeJsonErr("当前登录用户无法强退");
            }
            onlineSessionDao.delete(onlineSession);
            online.setStatus(OnlineSession.OnlineStatus.OFFLINE);
            userOnlineService.save(online);
            userOnlineService.removeUserCache(online.getLoginName(), sessionId);
        }
        return writeJsonOk();
    }
}
